package cai.a.viewpager3;

import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;
    private List<View> mViewList;
    private View view1;
    private View view2;
    private View view3;
    private View view4;
    private String[] mTitle = {"title1", "title2", "title3", "title4"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mViewPager = (ViewPager) findViewById(R.id.viewpager);

        LayoutInflater li = LayoutInflater.from(MainActivity.this);
        mViewList = new ArrayList<View>();

        view1 = li.inflate(R.layout.view1, null);
        view2 = li.inflate(R.layout.view2, null);
        view3 = li.inflate(R.layout.view3, null);
        view4 = li.inflate(R.layout.view4, null);

        mViewList.add(view1);
        mViewList.add(view2);
        mViewList.add(view3);
        mViewList.add(view4);

        PagerAdapter pagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return mViewList.size();
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mViewList.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(mViewList.get(position));
                return mViewList.get(position);
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTitle[position];
            }
        };

        mViewPager.setAdapter(pagerAdapter);
    }
}
